#pragma once
#include <iostream>
#include <unordered_map>
#include <functional>
#include <ctime>
#include <sys/types.h>
#include <unistd.h>

using namespace std;

using task_t = std::function<void()>;
static int number = 0;

void DownLoad()
{
    cout << "我是下载任务..., pid: " << getpid() << endl;
}

void Log()
{
    cout << "我是日志任务..., pid: " << getpid()  << endl;
}

void Sql()
{
    cout << "我是数据库任务..., pid: " << getpid()  << endl;
}

class TaskManger
{
public:
    TaskManger()
    {
        srand(time(nullptr)); // 设置随机数种子
        InsertTask(Log);
        InsertTask(Sql);
        InsertTask(DownLoad);
    }

    void InsertTask(task_t t)
    {
        _tasks[number++] = t;
    }

    int SelectTask()
    {
        return rand() % number;
    }

    void Excute(int num)
    {
        // 该任务不存在 返回
        if (_tasks.find(num) == _tasks.end())
            return;

        _tasks[num](); // 执行任务
    }

    ~TaskManger()
    {
    }

private:
    unordered_map<int, task_t> _tasks;
};

TaskManger tmg;

void Worker()
{
    // read->0
    while (true)
    {
        int cmd = 0;
        int n = ::read(0, &cmd, sizeof(cmd));
        if (n == sizeof(cmd))
        {
            tmg.Excute(cmd);
        }
        else if (n == 0)
        {
            // 当读到0时,意味着写端关闭,读到了文件结尾 子进程退出
            cout << "pid:" << getpid() << " quit..." << endl;
            break;
        }
        else
        {
        }
    }
}